from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app.models import User
from app import db
from datetime import datetime

bp = Blueprint('user', __name__, url_prefix='/user')

@bp.route('/')
@login_required
def index():
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    users = User.query.order_by(User.created_at.desc()).all()
    return render_template('user/index.html', users=users)

@bp.route('/add', methods=['GET', 'POST'])
@login_required
def add():
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    if request.method == 'POST':
        user = User(
            username=request.form.get('username'),
            email=request.form.get('email'),
            real_name=request.form.get('real_name'),
            phone=request.form.get('phone'),
            is_admin=request.form.get('is_admin') == 'on',
            status='active'
        )
        user.set_password(request.form.get('password'))
        
        try:
            db.session.add(user)
            db.session.commit()
            flash('用户添加成功', 'success')
            return redirect(url_for('user.index'))
        except Exception as e:
            db.session.rollback()
            if 'Duplicate entry' in str(e):
                if 'username' in str(e):
                    flash('用户名已存在', 'danger')
                elif 'email' in str(e):
                    flash('邮箱已存在', 'danger')
            else:
                flash('添加失败', 'danger')
    
    return render_template('user/add.html')

@bp.route('/<int:user_id>/edit', methods=['GET', 'POST'])
@login_required
def edit(user_id):
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    user = User.query.get_or_404(user_id)
    if request.method == 'POST':
        user.real_name = request.form.get('real_name')
        user.phone = request.form.get('phone')
        user.is_admin = request.form.get('is_admin') == 'on'
        
        if request.form.get('password'):
            user.set_password(request.form.get('password'))
        
        try:
            db.session.commit()
            flash('用户信息更新成功', 'success')
            return redirect(url_for('user.index'))
        except:
            db.session.rollback()
            flash('更新失败', 'danger')
    
    return render_template('user/edit.html', user=user)

@bp.route('/<int:user_id>/toggle', methods=['POST'])
@login_required
def toggle(user_id):
    if not current_user.is_admin:
        flash('权限不足', 'danger')
        return redirect(url_for('main.index'))
    
    user = User.query.get_or_404(user_id)
    if user.id == current_user.id:
        flash('不能禁用当前登录用户', 'danger')
    else:
        user.status = 'disabled' if user.status == 'active' else 'active'
        db.session.commit()
        flash(f'用户已{"禁用" if user.status == "disabled" else "启用"}', 'success')
    
    return redirect(url_for('user.index'))

@bp.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    if request.method == 'POST':
        current_user.real_name = request.form.get('real_name')
        current_user.phone = request.form.get('phone')
        
        if request.form.get('password'):
            current_user.set_password(request.form.get('password'))
        
        try:
            db.session.commit()
            flash('个人信息更新成功', 'success')
        except:
            db.session.rollback()
            flash('更新失败', 'danger')
    
    return render_template('user/profile.html') 